package com.bysc.joinservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bysc.baseservice.handler.BaiYunException;
import com.bysc.commonutils.ResultCode;
import com.bysc.commonutils.Results;
import com.bysc.commonutils.constant.MessageConstant;
import com.bysc.commonutils.utils.JwtUtils;
import com.bysc.commonutils.vo.JoinClubs;
import com.bysc.commonutils.vo.JoinClubsQueryVo;
import com.bysc.commonutils.vo.JoinUserDept;
import com.bysc.joinservice.entity.JoinDept;
import com.bysc.joinservice.service.JoinClubsService;
import com.bysc.joinservice.service.JoinDeptService;
import com.bysc.joinservice.service.JoinUserDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 社团表 前端控制器
 * </p>
 *
 * @author kkk
 * @since 2025-03-03
 */
@RestController
@Api(tags = "社团管理")
@RequestMapping("/joinservice/join-clubs")
public class JoinClubsController {

    @Autowired
    private JoinClubsService joinClubsService;
    @Autowired
    private JoinDeptService joinDeptService;
    @Autowired
    private JoinUserDeptService joinUserDeptService;


    /*
    * 新增和更新社团
    *
    * */
    @PostMapping("/addOrSaveClubs")
    @ApiOperation(value = "新增社团")
    public Results addOrSaveClubs(@RequestBody JoinClubs joinClubs, HttpServletRequest request){
        try {
            String TOKEN_clubId = JwtUtils.getClubIdByJwtToken(request);
            if(!StringUtils.isEmpty(TOKEN_clubId)){
                joinClubs.setId(TOKEN_clubId);
            }
            //调用service方法添加数据
            joinClubsService.save(joinClubs);
            return Results.ok().message(MessageConstant.CLUBS_ADD_SUCCESS);
        }
        catch (Exception e){
            return Results.error().message(MessageConstant.CLUBS_ADD_FAIL);
        }
    }


    /*
    * 分页查询社团
    * */
    @PostMapping("/getClubsByPage/{page}/{limit}")
    @ApiOperation(value = "分页查询社团")
    public Results getClubsByPage( @ApiParam(name = "page", value = "查询页数", required = true)@PathVariable Integer page,
                                   @ApiParam(name = "limit", value = "查询数量", required = true) @PathVariable Integer limit,
                                   @RequestBody(required = false)  JoinClubsQueryVo joinClubsQuery, HttpServletRequest request)
    {

        try {
            Page<JoinClubs> pageClubs = new Page<>(page, limit);
            LambdaQueryWrapper<JoinClubs> wrapper = new LambdaQueryWrapper<>();
            if (joinClubsQuery != null) {
                String clubId = joinClubsQuery.getId();
                if (!StringUtils.isEmpty(clubId)) {
                    wrapper.eq(JoinClubs::getId, clubId);
                }
                String name = joinClubsQuery.getName();
                if (!StringUtils.isEmpty(name)) {
                    wrapper.like(JoinClubs::getName, name);
                }
                String place = joinClubsQuery.getPlace();
                if (!StringUtils.isEmpty(place)) {
                    wrapper.like(JoinClubs::getPlace, place);
                }
                String description = joinClubsQuery.getDescription();
                if (!StringUtils.isEmpty(description)) {
                    wrapper.like(JoinClubs::getDescription, description);
                }
            }
            String TOKEN_clubId = JwtUtils.getClubIdByJwtToken(request);
            if(!StringUtils.isEmpty(TOKEN_clubId)){
                wrapper.eq(JoinClubs::getId, TOKEN_clubId);
            }
            IPage<JoinClubs> pageModel = joinClubsService.page(pageClubs, wrapper);
            return Results.ok().data("JoinClubsByPage", pageModel).message(MessageConstant.GET_CLUBS_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.GET_CLUBS_FAIL);
        }
    }

    /*
    * 查询社团
    * */
    @PostMapping("/getClubs/{clubId}")
    @ApiOperation(value = "根据clubld查询社团（仅前台）")
    public Results getClubs(@PathVariable String clubId){
        try{
            return Results.ok().data("JoinClubs",joinClubsService.getById(clubId)).message(MessageConstant.GET_CLUBS_SUCCESS);
        }
        catch (Exception e){
            throw new BaiYunException( ResultCode.ERROR, MessageConstant.GET_CLUBS_FAIL);
        }
    }

    /*
    * 后台查看社团
    * */
    @PostMapping("/getSelfClubs")
    @ApiOperation(value = "社团负责人查询自己社团")
    public Results getClubs(HttpServletRequest request){
        try {
            String TOKEN_clubId = JwtUtils.getClubIdByJwtToken(request);
            if(!StringUtils.isEmpty(TOKEN_clubId)){
                JoinClubs joinClubs = joinClubsService.getById(TOKEN_clubId);
                return Results.ok().data("JoinClubs",joinClubs).message(MessageConstant.GET_CLUBS_SUCCESS);
            }
            return Results.error().message(MessageConstant.GET_CLUBS_FAIL);
       }
        catch (Exception e){
            throw  new BaiYunException(ResultCode.ERROR, MessageConstant.GET_CLUBS_FAIL);
        }
    }

    /*
    * 根据clubId
    * 查询社团负责人
    * */
    @PostMapping("/getClubLeader/{clubId}")
    @ApiOperation(value = "根据clubld查询社团负责人")
    public Results getClubLeader(@PathVariable String clubId) {
        try {
            //用clubId查询出社团部门的id后查出部门负责人的id
            LambdaQueryWrapper<JoinDept> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(JoinDept::getClubId, clubId);
            JoinDept joinDept = joinDeptService.getOne(wrapper);//拿到部门
            if(joinDept==null){
                return Results.error().message("社团负责人为空");
            }

            LambdaQueryWrapper<JoinUserDept> wrapperUser = new LambdaQueryWrapper<>();
            wrapperUser.eq(JoinUserDept::getClubId, joinDept.getClubId());//查出部门用户关系表
            wrapperUser.eq(JoinUserDept::getIsLeader, 1);//查出部门负责人
            String leader=joinUserDeptService.getOne(wrapperUser).getUserName();
            if(leader==null){
                return Results.error().message("社团负责人为空");
            }
            return Results.ok().data("leader",leader).message(MessageConstant.GET_CLUBS_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.GET_CLUBS_FAIL);
        }
    }




    /*
    * 查询前六条社团信息
    * */
    @GetMapping("/getSomeClubs")
    @ApiOperation(value = "查询前六条社团信息")
    public Results getAllClubs(){
        try{
            List<JoinClubs> clubsList = joinClubsService.list(new QueryWrapper<JoinClubs>().orderByDesc("gmt_create"));
            return Results.ok().data("JoinClubsByList", clubsList).message(MessageConstant.GET_CLUBS_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.GET_CLUBS_FAIL);
        }
    }


    /*
     * 修改社团信息
     * */
    @PostMapping("/updateClubs")
    @ApiOperation(value = "修改社团信息")
    public Results updateClubs(@RequestBody JoinClubs joinClubs) {
        try {
            joinClubsService.updateById(joinClubs);
            return Results.ok().message(MessageConstant.UPDATE_CLUBS_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.UPDATE_CLUBS_FAIL);
        }
    }

    /*
     * 根据id删除社团信息
     * */
    @DeleteMapping("/deleteClubsById/{clubId}")
    @ApiOperation(value = "根据id删除社团信息")
    public Results deleteClubsById(@PathVariable String clubId) {
        try {
            joinClubsService.removeById(clubId);
            return Results.ok().message(MessageConstant.DELETE_CLUBS_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.DELETE_CLUBS_FAIL);
        }
    }


}

